package com.baosight.xCyber.util;

import com.baosight.ice.util.ConfLoader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Reader;
import java.util.Properties;

/**
 * mybatis连接数据库的常用工具类
 * @author 吴起航
 */
public class SqlSessionFactoryUtil {
    private static Logger logger = LoggerFactory.getLogger(SqlSessionFactoryUtil.class);
    private static SqlSessionFactory sqlSessionFactory = null;
    private static String mybatisPath = "mybatis-config-tree.xml";
    private static String dbcpPath = "application.properties";
    private static Properties properties;
    private static Reader reader;

    static {
        try {
            reader = Resources.getResourceAsReader("mybatis-config.xml");

        } catch (Exception e) {
            logger.error(mybatisPath + " load failed");
        }
        properties = ConfLoader.getPropertie(dbcpPath);
    }

    //通过SqlSessionFactoryBuilder对象的build方法获得单例SqlSessionFactory工厂对象

    private static SqlSessionFactory getSqlSessionFactory(){
        if(sqlSessionFactory == null){
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader,properties);
        }
        return sqlSessionFactory;
    }

    public static SqlSession getSqlSession(){
        SqlSession session = getSqlSessionFactory().openSession();
        return session;
    }
    
}
